package com.jacksen.demo.view.aidl;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 远程服务端service, 该service运行在其他进程中（manifest中配置）
 */

public class DownloadService extends Service {

    private AtomicBoolean isServiceDestroyed = new AtomicBoolean(false);
    //    private CopyOnWriteArrayList<IDownloadListener> listeners = new CopyOnWriteArrayList<>();
    private RemoteCallbackList<IDownloadListener> listeners = new RemoteCallbackList<>();

    private AtomicInteger progress = new AtomicInteger();

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isServiceDestroyed.set(true);
    }

    private class ServiceWorker implements Runnable {

        @Override
        public void run() {
            while (!isServiceDestroyed.get()) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                progress.addAndGet(2);

                try {
                    updateProgress();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void updateProgress() throws RemoteException {
       /* for (IDownloadListener listener : listeners) {
            listener.onDownloadProgress(progress.get());
        }*/

        int n = listeners.beginBroadcast();
        for (int i = 0; i < n; i++) {
            listeners.getBroadcastItem(i).onDownloadProgress(progress.get());
        }
        listeners.finishBroadcast();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private Binder binder = new IDownloadService.Stub() {
        @Override
        public int getPid() throws RemoteException {
            return 123;
        }

        @Override
        public TestAidlBean getAidlBean(String name) throws RemoteException {
            return new TestAidlBean(name, 25);
        }

        @Override
        public void startDownload(String url) throws RemoteException {
            Log.d("DownloadService", url + "--开始下载");
            new Thread(new ServiceWorker()).start();
        }

        @Override
        public void registerListener(IDownloadListener listener) throws RemoteException {
            /*if (listeners.contains(listener)) {
                Log.d("DownloadService", "already exists");
            } else {
                listeners.add(listener);
            }*/
            listeners.register(listener);
        }

        @Override
        public void unregisterListener(IDownloadListener listener) throws RemoteException {
            /*if (listeners.contains(listener)) {
                listeners.remove(listener);
            } else {
                Log.d("DownloadService", "not found");
            }*/
            listeners.unregister(listener);
        }

    };

}